package com.sc.web.goods;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sc.dal.dto.goods.GoodsClassMap;
import com.sc.dal.mapper.goods.GoodsClassMapper;
import com.sc.dal.model.goods.GoodsClass;
import com.sc.dal.model.system.UserFormMap;
import com.sc.service.goods.GoodsClassService;
import com.sc.util.data.Common;
import com.sc.util.data.DataUtil;
import com.sc.util.data.TreeObject;
import com.sc.util.data.TreeUtil;
import com.sc.util.exception.ExceptionEnum;
import com.sc.web.BaseController;

/**
 * 商品分类管理
 * @author xiongyong
 * @日期 Mar 20, 2017 10:22:35 AM
 */
@Controller
@RequestMapping(value="/goodsClass")
public class GoodsClassController extends BaseController{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private GoodsClassService goodsClassService;
	@Autowired
	private GoodsClassMapper goodsClassMapper;
	
	
	@RequestMapping("/initGoodsClass")
	public String initGoodsClass(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		return "/goods/goodsClass/goodsClassList";
	}

	
	@RequestMapping("/selectByTreeList")
	@ResponseBody
	public Object selectByTreeList(){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//设置查询参数
		Map<String,Object> paramMap = new HashMap<String,Object>();
		List<GoodsClass> goodsClassList = this.goodsClassService.selectList(paramMap);
		logger.debug("goodsClassList.size():"+goodsClassList.size());
		List<GoodsClass> treeList = new ArrayList<GoodsClass>();
		/**
         * 将List转换树结构 
         */
        for (GoodsClass menu : goodsClassList) {
            boolean mark = false;
            for (GoodsClass menuTemp : goodsClassList) {
                 if(menuTemp.getId().equals(menu.getParentId())){
                      mark =true;
                      if(menuTemp.getChildren() == null){
                    	  menuTemp.setChildren(new ArrayList<GoodsClass>());
                      }
                      menuTemp.getChildren().add(menu);
                      break;  //跳出当前循环
                 }
            }
            if(!mark){
            	treeList.add(menu);
            }
        }
        resultMap.put("treeList", treeList);
		return resultMap;
	}
	
	
	
	/**
	 * 初始化app端一级商品分类页面
	 * @return
	 */
	@RequestMapping(value="/permissions")
	@ResponseBody
	public Object permissions(){
		ModelAndView mav = new ModelAndView("/goods/goodsClass/appByGoodsClass");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String parentId = "";
		paramMap.put("parentId", parentId);
		List<GoodsClass> goodsClass = goodsClassService.selectByGoodsClass();
		mav.addObject("goodsClass", goodsClass);
		return mav;
	}
	
	/**
	 * 提交商品分类的的状态，控制app端一级分类的显示
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/subGoodsClassByApp")
	@ResponseBody
	public Object subGoodsClassByApp(HttpServletRequest request){
		String chkValue = request.getParameter("chkValue");
		List<Long> listV = new ArrayList<Long>();
		logger.debug("请求url成功--------------------------------------------"+chkValue);
		String status = "";
		String []tempValue = chkValue.split(",");
		for (int i = 0; i < tempValue.length; i++) {
			listV.add(Long.valueOf(tempValue[i]));
			
		}
		int i = goodsClassService.editGoodsClassStatus(listV);
		if(i!=0){
			return "SUCCESS";
		}else{
			return "ERRO";
		}
		
	}
	
	
	@RequestMapping(value="/addGoodsClass")
	@ResponseBody
	public Object addGoodsClass(){
		ModelAndView mav = new ModelAndView("/goods/goodsClass/andGoodsClass");
		return mav;
	}
	
	
	/***
	 * 提交新增商品分类
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/subAddGoodsClass")
	@ResponseBody
	public Object subAddGoodsClass(HttpServletRequest request){
		int i;
		GoodsClass goodsClass = new GoodsClass();
		String classID = request.getParameter("classID");
		//从session里获取用户的登录信息
		UserFormMap user = (UserFormMap) request.getSession().getAttribute("userSession");
		 //获取分类名称
		String name = request.getParameter("goodsClassMap.name");
		if(StringUtils.isNotBlank(name)){
			goodsClass.setName(name);
		}
		//分类code
		String code = request.getParameter("goodsClassMap.code");
		if(StringUtils.isNotBlank(code)){
			goodsClass.setCode(code);
		}
		//商品图标
		String icon = request.getParameter("goodsClassMap.icon");
		if(StringUtils.isNotBlank(icon)){
			goodsClass.setIcon(icon);
		}
		//商品上级分类
		String parentId = request.getParameter("goodsClassMap.parentId");
		if(parentId!=null && "0".equals(parentId)){
			//goodsClass.setParentId(new Integer(null));
			goodsClass.setDepth(new Byte("1"));
		//修改父级节点
		}else if(parentId==null){
			goodsClass.setDepth(new Byte("1"));
		}else{
			goodsClass.setParentId(new Integer(parentId));
			//节点层级,,根据当前节点ID,去查询上级父节点ID
			GoodsClass goods = goodsClassService.selectByPrimaryKey(new Integer(parentId));
			Byte depth = goods.getDepth();
			int depthT = Byte.valueOf(depth)+1;
			goodsClass.setDepth(new Integer(depthT).byteValue());
		}
		//分类排序
		String sortNumber = request.getParameter("goodsClassMap.sortNumber");
		if(sortNumber!=null && !"".equals(sortNumber)){
			goodsClass.setSortNumber(new Integer(sortNumber));
		}
		//是否子节点
		String isEndNode = request.getParameter("goodsClassMap.isEndNode");
		goodsClass.setIsEndNode(isEndNode);  //是否末级节点（1：是；0：否）',
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //创建时间
		//根据ID判断是否，id为空 新增数据，否则更新数据
		if(classID!=null && !"".equals(classID)){
			goodsClass.setId(new Integer(classID));
			goodsClass.setModifier(user.getStr("accountName"));  //修改人
			goodsClass.setModifyTime(sdf.format(new Date()));  //修改时间
			i = goodsClassService.updateGoodsClass(goodsClass);
		}else{
			goodsClass.setCreater(user.getStr("accountName")); //创建人
			goodsClass.setCreateTime(sdf.format(new Date()));  //创建时间
			goodsClass.setModifier(user.getStr("accountName"));  //修改人
			goodsClass.setModifyTime(sdf.format(new Date()));  //修改时间
			goodsClass.setIsDelete("0");  //0 ,未删除
			i = goodsClassService.insertGoodsClass(goodsClass);
		}
		
		if(i>0){
			return "success";
		}
		return "error";
	}
	
	/***
	 * 跳转商品分类编辑页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/editGoodsClass")
	@ResponseBody
	public Object editGoodsClass(HttpServletRequest request){
		logger.warn("id:"+request.getParameter("id"));
		ModelAndView  mav = new ModelAndView("/goods/goodsClass/editGoodsClass");
		String id = request.getParameter("id");
		GoodsClass goodsClass = goodsClassService.selectByPrimaryKey(new Integer(id));
		if(goodsClass.getParentId()==null){
			goodsClass.setParentId(0);
		}
		mav.addObject("goodsClass", goodsClass);
		return mav;
	}
	
	
	
	
	@RequestMapping(value="/initTree")
	@ResponseBody
	public Object initTree(){
		//设置查询参数
//		ParamMap paramMap = getFormMap(ParamMap.class);
//		Map<String,Object> paramMap = new HashMap<String,Object>();
//		List<ParamMap> goodsClassList = this.goodsClassService.selectList(paramMap);
		/*logger.debug("goodsClassList.size():"+goodsClassList.size());
		List<GoodsClass> treeList = new ArrayList<GoodsClass>();
		*//** 将List转换树结构 *//*
        for (GoodsClass menu : goodsClassList) {
            boolean mark = false;
            for (GoodsClass menuTemp : goodsClassList) {
                 if(menuTemp.getId().equals(menu.getParentId())){
                      mark =true;
                      if(menuTemp.getChildren() == null){
                    	  menuTemp.setChildren(new ArrayList<GoodsClass>());
                      }
                      menuTemp.getChildren().add(menu);
                      break;  //跳出当前循环
                 }
            }
            if(!mark){
            	treeList.add(menu);
            }
        }
        return treeList;*/
        
		Map<String,Object> paramMap = new HashMap<String,Object>();
		List<GoodsClassMap> goodsClassList = this.goodsClassService.queryGoodsClassList(paramMap);
		
        
		/*GoodsClassMap resFormMap = getFormMap(GoodsClassMap.class);
		List<GoodsClassMap> mps = goodsClassMapper.findByWhere(resFormMap);*/
		
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (GoodsClassMap map : goodsClassList) {
			TreeObject ts = new TreeObject();
			Common.flushObject(ts, map);
			list.add(ts);
		}
		for (TreeObject treeObject : list) {
			Integer parentId =  treeObject.getParentId();
			if(parentId == null){
				treeObject.setParentId(0);
			}
		}
		TreeUtil treeUtil = new TreeUtil();
		
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0, " ");
		return ns;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 根据id，查找商品分类
	 * @param id
	 * @return Map<String, Object>
	 */
	@RequestMapping(value="/selectGoodsClass", method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> selectGoodsClass(Integer id) {
		Map<String, Object> resultMap = new LinkedHashMap<String,Object>();
		if(id==null){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
			logger.warn("查找参数有误！");
		}else{
			try{
				GoodsClass goodsClass = this.goodsClassService.selectByPrimaryKey(id);
				if(goodsClass!=null){
					resultMap.put("data", goodsClass);
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
					logger.warn("查找商品分类成功！");
				}else{
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
					logger.warn("查找商品分类失败！");
				}
			}catch (Exception e){
				e.printStackTrace();
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
				logger.warn("查找商品分类出错！");
			}
		}
		
		return resultMap;
	}
	
	/**
	 * 查找所有商品分类
	 * @return Map<String, Object>
	 */
	@RequestMapping(value="/selectList")
	@ResponseBody
	public Map<String, Object> selectList(HttpServletRequest request) {
		Map<String, Object> resultMap = new LinkedHashMap<String,Object>();
		//设置查询参数
		Map<String,Object> paramMap = new HashMap<String,Object>();
		String depth = request.getParameter("depth");
		String parentId = request.getParameter("parentId");
		if(StringUtils.isNotBlank(depth)){	//商品名称
			paramMap.put("depth", depth);
		}
		if(StringUtils.isNotBlank(parentId)){	//商品名称
			paramMap.put("parentId", parentId);
		}
		
		try{
			List<GoodsClass> goodsClassList = this.goodsClassService.selectList(paramMap);
			if(goodsClassList!=null && goodsClassList.size()>0){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
				resultMap.put("data", goodsClassList);
				logger.warn("查找所有商品分类成功！");
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
				logger.warn("查找所有商品分类失败！");
			}
		}catch (Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.warn("查找所有商品分类出错！");
		}
		
		return resultMap;
	} 
	
	
	/*****
	 * 校验商品分类名称是否存在
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/isClassNameExist")
	@ResponseBody
	public boolean isClassNameExist(HttpServletRequest request){
		String name= request.getParameter("name");
		String id = request.getParameter("id");
		Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
		if(name!=null){
			paramMap.put("className", name);
			List<GoodsClass> goodsClassList = this.goodsClassService.selectList(paramMap);
			//编辑校验
			if(Common.isNotEmpty(id)){
				if(goodsClassList!=null && goodsClassList.size()>0){
					String idd = goodsClassList.get(0).getId().toString();
					if(idd!=null && id.equals(idd)){
						return true;
					}
					return false;
				}else{
					return true;
				}
			//新增校验
			}else{
				if(goodsClassList!=null && goodsClassList.size()>0){
					return false;
				}else{
					return true;
				}
			}
		}else{
			return false;
		}
	}
}
